<template>
	<div v-show="visible">
		<van-field readonly clickable :label="componentModel.label" v-model="vue_model_label" @click="showPicker()" />
		<van-popup v-model:show="showPicker_model" position="bottom">
			<van-datetime-picker v-model="vue_model" type="date" @cancel="closePicker()" @confirm="onConfirm" />
		</van-popup>
	</div>
</template>

<script>
	import {
		sendComponentValueChangeRequest
	} from '@/utils/requestUtils.js';
	import utils from '@/utils/utils.js';
	export default {
		name: "DateComponent",
		props: ["componentModel", "scope"],
		data() {
			return {
				vue_model: "",
				vue_model_label: "",
				showPicker_model: false,
				visible: true,
				readonly: false,
				label: "",
			}
		},
		inject: ['children'],
		mounted() {
			this.children.push(this);
		},beforeUnmount() {
			utils.removeArrayElement(this.children,this);
		},
		methods: {
			onConfirm(value) {
				var sMonth = value.getMonth() + 1 + "";
				if (value.getMonth() + 1 < 10) {
					sMonth = "0" + (value.getMonth() + 1);
				}
				var sDate = value.getDate() + "";
				if (value.getDate() + 1 < 10) {
					sDate = "0" + value.getDate();
				}

				this.vue_model_label = value.getFullYear() + "-" + sMonth + "-" + sDate;
				this.showPicker_model = false;
				this.onValueChangeHandler();
			},
			getValue() {
				return this.vue_model_label;
			},
			setProp(prop) {
				for (var k in prop) {
					if (k == "value") {
						if (prop[k] == null) {
							this.vue_model = new Date();
							this.vue_model_label = "";
						} else {
							var dateArray = prop[k].split("-");
							this.vue_model = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]);
							this.vue_model_label = prop[k];
						}
					} else if (k == "visible") {
						this.visible = prop[k];
					} else if (k == "readonly") {
						this.readonly = prop[k];
					} else if (k == "label") {
						this.label = prop[k];
					}
				}
			},
			onValueChangeHandler() {
				if (this.scope != undefined) {
					this.$emit("onValueChange", this);
					return;
				}
				sendComponentValueChangeRequest(this);
			},
			showPicker() {
				if (this.readonly) {
					return;
				}
				this.showPicker_model = true;
			},
			closePicker() {
				this.showPicker_model = false
			}
		}
	}
</script>

<style>
</style>
